package ch.bfh.mobicomp.soda2.temperature;

import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		SharedPreferences sharedPreferences = getSharedPreferences(
				SODATemperatureDataCollectorService.getSharedPreferencesName(), MODE_PRIVATE);
		sharedPreferences
				.registerOnSharedPreferenceChangeListener(new TemperaturePreferenceChange());
		Intent serviceIntent = SODATemperatureDataCollectorService.getStartIntent(this,
				System.currentTimeMillis());
		startService(serviceIntent);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	enum Status {
		clear, taintedTime, taintedTemp, fresh;
	}

	class TemperaturePreferenceChange implements
			OnSharedPreferenceChangeListener {

		private long latestTimeStamp;
		private int latestTemperature;
		private Status status;

		@Override
		public void onSharedPreferenceChanged(
				SharedPreferences sharedPreferences, String key) {
			Log.i(SODATemperatureDataCollectorService.TAG, "SharedPrefs: " + key);
			if (key.equals(SODATemperatureDataCollectorService.TEMPERATURE_STATUS_EXTRA_AT_TIME_IN_SECONDS)) {
				latestTimeStamp = sharedPreferences
						.getLong(key, Long.MIN_VALUE);
				if (status == Status.taintedTemp) {
					status = Status.fresh;
				} else
					status = Status.taintedTime;
			}
			if (key.equals(SODATemperatureDataCollectorService.BATTERY_STATUS_EXTRA_TEMPERATURE)) {
				latestTemperature = sharedPreferences.getInt(key,
						Integer.MIN_VALUE);
				if (status == Status.taintedTime) {
					status = Status.fresh;
				} else
					status = Status.taintedTemp;
			}
			if (status == Status.fresh) {
				status = Status.clear;
				Toast.makeText(
						MainActivity.this,
						"Changed: Temp: " + latestTemperature + " @: "
								+ latestTimeStamp, Toast.LENGTH_LONG).show();

			}
		}

	}

}
